class_name OldPlayer
extends CharacterBody2D

@export var speed: float = 200.0
@export var health: int = 20

@onready var dead_ui: CanvasLayer = %Dead
@onready var win_ui: CanvasLayer = %Win
@onready var health_ui: Label = %Health

var mouse_left_pressed:bool= false
var mouse_right_pressed:bool = false

signal on_die(player: Player)

func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			mouse_left_pressed = true
		if event.button_index == MOUSE_BUTTON_RIGHT and event.pressed: 
			mouse_right_pressed = true

func _physics_process(delta: float) -> void:
	if mouse_left_pressed:
		for body in $Area2D.get_overlapping_bodies():
			if body is Enemy:
				
				body.die()
	if mouse_right_pressed:
		var cobee = preload("res://scene/cobee_man.tscn").instantiate()
		cobee.position = $Area2D.global_position
		get_parent().add_child(cobee)
		health -= 1
	mouse_left_pressed = false
	mouse_right_pressed = false
	# Handle player movement
	velocity = Vector2.ZERO
	if Input.is_key_pressed(KEY_D) || Input.is_key_pressed(KEY_RIGHT):
		velocity.x += 1
	if Input.is_key_pressed(KEY_A) || Input.is_key_pressed(KEY_LEFT):
		velocity.x -= 1
	if Input.is_key_pressed(KEY_W) || Input.is_key_pressed(KEY_UP):
		velocity.y -= 1
	if Input.is_key_pressed(KEY_S) || Input.is_key_pressed(KEY_DOWN):
		velocity.y += 1

	# Normalize the velocity vector to ensure consistent speed in all directions
	if velocity.length() > 0:
		velocity = velocity.normalized() * speed
	_follow_mouse(delta)
	move_and_slide()
	
	health_ui.text = str(health)
	if health <= 0:
		on_die.emit(self)
		dead_ui.show()
		pause_game()

func hurt():
	if health > 0: health -= 1

func win() -> void:
	win_ui.show()
	pause_game()

func pause_game() -> void:
	get_tree().paused = true

func _follow_mouse(_delta):
	var target =global_position+ get_viewport().get_mouse_position()-0.5*DisplayServer.window_get_size(0)
	if (target - global_position).length() > 180:
		target = global_position + (target - global_position).normalized() * 180
	$Area2D.global_position = target
	#$Area2D.look_at(self.global_position)
